var myiscroll=null;
var pageData = {},
    stafArray = new Array();
var report_date="";


function init (){
	ClearOkPf();
	$("#content").hide();
	$("#loading").show();
    $.ajax({
        type: "post",
        url: mpsurl+"/mobile/report/queryGradePrompt.do",
        dataType: "json",
        data: {method:"getGradeStaff"},
        success: function(data){
        	$("#loading").hide();
            initGradeStaff(data);
        },
        error: function(XMLHttpRequest,textStatus,errorThrown){
            //alert(errorThrown);
            $("#loading").hide();
           // errorMask(errorThrown||"请求失败");
           setPromptForInput("网络异常");
        }
    });
    //initGradeStaff(gradeDATA);
    
    //解析url,获取汇报日期
    /*
    var url = location.href.split('?')[1];
	if(url!=null){
		var arr = url.split('&');
		for(var i = 0 ; i < arr.length;i++){
			var temp = arr[i];
			var tempArr = temp.split('=');
			var key = tempArr[0];
			if(key == "report_date"){
				report_date=tempArr[1];
			}
		}
	}*/
	report_date = getQueryParam("report_date");
	$("#month").html(report_date.substr(5,2));

    //$("#month").text(formatDate(new Date().getMonth()+1));
    $("#errorMask").tap(function(){
		$("#errorMask").hide();
		//history.back(-1);
	});
}

/**
 * 获取数据
 */
function loadPageData () {
	//$("#loading").show();
    $.ajax({
        url : mpsurl+"/mobile/report/queryMyReportGrade.do",
        dataType : "json",
        data : {
    		method:"kpi-toScore",
            report_date : report_date
        },
        type: "post",
        success : function(data){
        	//$("#loading").hide();
            if(data.resultCode=="500600"){
            	GetOkPf();
        		$("#content").show();
	            pageData = data.value;
	            //renderPageData(data);
	            //汇报状态
	            var staArr = {"USUB":"未提交","SUBM":"待确认","APP":"已确认","BAC":"已驳回","NON":"未制定"};
			    var reportStatus = pageData.report.pAIC_MON_STATUS;
			    
			    //已驳回,显示意见及评分
	            if(reportStatus == "BAC"){
	            	var reportGrade = pageData.reportGrade;
					var report = pageData.report;
	            	var manager1_name = report.manager1_name;
					var manager2_name = report.manager2_name;
					var manager3_name = report.manager3_name;
					
	            	var div2=$("<li>"+
			            "<div class=\"info-list-cont\">"+
			            "<p>主考核人："+manager1_name+" <span class=\"fn-c-999\">评分：</span><span class=\"fn-c-fa4043\">"+reportGrade.assess1_grade5+"</span></p>"+
			            "<p style=\"word-break: break-all;\"><span class=\"fn-c-999\">意见：</span>"+reportGrade.assess1.replace(/\n/g,"<br>")+"</p>"+
			            "</div>"+
			            "</li>");
			         $("#khbac").append(div2);
	            	if(report.ep_manager2_status=="Y"){
						var eP_MANAGER2_ID = report.eP_MANAGER2_ID;
						if(eP_MANAGER2_ID.replace(/(^\s*)|(\s*$)/g, "")!=""){
							div2 = $("<li>"+
								   "<div class=\"info-list-cont\">"+
			                       "<p>第二考核人："+manager2_name+" <span class=\"fn-c-999\">评分：</span><span class=\"fn-c-fa4043\">"+reportGrade.assess2_grade5+"</span></p>"+
			                       "<p style=\"word-break: break-all;\"><span class=\"fn-c-999\">意见：</span>"+reportGrade.assess2.replace(/\n/g,"<br>")+"</p>"+
			                       "</div></li>");
			                $("#khbac").append(div2);
						}
					}
					if(report.ep_manager3_status=="Y"){
						/** 如果有第三审核人 就显示!*/
						if(report.eP_MANAGER3_ID.replace(/(^\s*)|(\s*$)/g, "")!=""){
					          var div3=$("<li><div class=\"info-list-cont\">"+
					          "<p>第三考核人："+manager3_name+" <span class=\"fn-c-999\">评分：</span><span class=\"fn-c-fa4043\">"+reportGrade.assess3_grade5+"</span></p>"+
					          "<p style=\"word-break: break-all;\"><span class=\"fn-c-999\">意见：</span>"+reportGrade.assess3.replace(/\n/g,"<br>")+"</p>"+
					          "</div></li>");
					          $("#khbac").append(div3);
					    }
				    }
					$("#firstReview").show();
	            }
				for(var perSta in staArr){
					if(perSta == reportStatus){
						reportStatus = staArr[perSta];
					}
				}
				var managername = pageData.report.manager1_name;
    			$("#managername").html(managername);
				
	            $("#report_status").html(reportStatus);
	            renderPage();
	            //标尺
	            var self = pageData.reportGrade.self_grade5;
	            $("#J-StaffNum").text(self);
	            if(self=="" || self=="0" || self == null)
	            	$("#J-StaffNum").text("...");
	    		setOpinionMsg(self);
    		}else{
    			var tourl = "/mobile/kpi/kpi-toScore.html?report_date="+report_date;
            	checkLogin(data.resultCode,tourl,data.resultMessage);
    		}
        },
        error : function(){
			//$("#loading").hide();
			//errorMask("网络异常");
			setPromptForInput("网络异常");
        }
    });
   // pageData = DATA.value;
    //renderPage();
}

/**
 * 渲染KPI页面数据
 */
function renderPage () {
	if(pageData.iscyc=="1"){
		if(pageData.ewg.length==0){
			$(".kpi-module").hide();
		}else{
		    var tpl = $("#keywork-item-tpl").html(), dot = doT.template(tpl);
		    $("#keyworkList").prepend(dot(pageData.ewg));
		    countSum();
	    }
    }else{
    	$(".kpi-module").hide();
    }
}

function bindEvent (){
    $("#save").on("tap", save);
    $("#submit").on("tap", submit);
    $("#mask-cancel").on("tap", function(){
        $("#maskNode").hide();
        GetOkPf();
    });
    $("#mask-sure").on("tap", function(){
    	$("#maskNode").hide();
        submitData();
    });
    
    //汇报状态提示
    $("#report_status").on("tap",function(){
    	var status = pageData.report.pAIC_MON_STATUS;
    	var manager1_name = pageData.report.manager1_name;
    	var month="";
    	month = report_date.substr(5,2);
    	var message="";
    	if(status=="USUB")
    		message="您的"+month+"月汇报还未提交，提交后将由"+manager1_name+"审批。";
    	else if(status=="SUBM")
    		message="您的"+month+"月汇报已提交，将由"+manager1_name+"确认。";
    	else if(status=="APP")
    		message="您的"+month+"月汇报已由"+manager1_name+"确认。";
    	else if(status=="BAC")
    		message="您的"+month+"月汇报已被"+manager1_name+"驳回，重新提交后将由"+manager1_name+"审批";
    	else if(status=="NON")
    		message="您的"+month+"月汇报还未制定，制定后将由"+manager1_name+"审批。";
    	errorMask(message);
    });
}
function save(){
//    if(!check()){
//        return;
//    }
	ClearOkPf();
    var submitParams,
        grade={
            "EP_APPRAISAL_ID" : pageData.report.ep_appraisal_id || "",
            "EP_RATING_MON" : $("#J-StaffNum").text(),
            "EP_RATING_M_A" : $("#opinionMsg").attr("data-rd"),
            "EP_RATING_M_B" : $("#opinionMsg").text(),
            "MONTH_EP" : pageData.report.eVA_MONTH_EP || "",
            "YEAR_EP" : pageData.report.yEAR_EP || "",
            "PAIC_SUM_SELF_RATE" : $("#totalScore").text()
        };
     var five = "";
     var EP_RATING_M_A=" ";
     var EP_RATING_M_B=" ";
    if($("#J-StaffNum").text()=="..."){
    	five="0";
    	EP_RATING_M_A=" ";
    	EP_RATING_M_B=" ";
    }
    else{
    	five = $("#J-StaffNum").text();
    	EP_RATING_M_A=$("#opinionMsg").attr("data-rd");
    	EP_RATING_M_B=$("#opinionMsg").text();
    }
    var grade_str = "{'EP_APPRAISAL_ID':'"+ pageData.report.ep_appraisal_id +"',"+
            "'EP_RATING_MON':'" + five +"',"+
            "'EP_RATING_M_A':'" + EP_RATING_M_A +"',"+
            "'EP_RATING_M_B':'" + EP_RATING_M_B +"',"+
            "'MONTH_EP':'" + pageData.report.eVA_MONTH_EP  +"',"+
            "'YEAR_EP':'" + pageData.report.yEAR_EP +"',"+
            "'PAIC_SUM_SELF_RATE':'" + $("#totalScore").text() +"'}";

    $(".edit-score").forEach(function(node){
        node = $(node);
        var index = node.attr("data-index");
        pageData.ewg[index].ewg_self_rating = node.val();
    });
    
    var reportObj = pageData.report;
    
    var report_src = "{'EMPLID':'" + reportObj.eMPLID + "'," +
    "'EP_APPRAISAL_ID':'" + reportObj.ep_appraisal_id + "'," +
    "'EP_MANAGER1_ID':'" + reportObj.eP_MANAGER1_ID + "'," +
    "'EP_MANAGER2_ID':'" + reportObj.eP_MANAGER2_ID + "'," +
    "'EP_MANAGER3_ID':'" + reportObj.eP_MANAGER3_ID + "'," +
    "'EP_TEMPLATE_ID':'" + reportObj.eP_TEMPLATE_ID + "'," +
    "'EVA_GROUP_ID':'" + reportObj.eVA_GROUP_ID + "'," +
    "'GRADED_CYC':'" + reportObj.gRADED_CYC + "'," +
    "'MONTH_EP':'" + reportObj.eVA_MONTH_EP + "'," +
    "'PAIC_MON_STATUS':'" + reportObj.pAIC_MON_STATUS + "'," +
    "'YEAR_EP':'" + reportObj.yEAR_EP + "'}";
    
    var ewg_str="";
    var ewgObj = pageData.ewg;
    for(var i=0;i<ewgObj.length;i++){
    	ewg_str = ewg_str +"{'CONTENT_DESCR':'"+ewgObj[i].ewg_descr+"',"+
    	"'EP_APPRAISAL_ID':'" + reportObj.ep_appraisal_id + "'," +
        "'EP_TRK_STATUS':'" + ewgObj[i].ewg_status + "'," +
        "'EVA_WEIGHT':'" + ewgObj[i].ewg_weight + "'," +
        "'PAIC_SELF_RATING':'" + ewgObj[i].ewg_self_rating + "'," +
        "'MONTH_EP':'" + reportObj.eVA_MONTH_EP + "'," +
        "'PAIC_EP_RESERVED1':'" + ewgObj[i].ewg_rea + "'," +
        "'PAIC_EP_RESERVED2':'" + ewgObj[i].ewg_nco + "'," +
        "'PAIC_EP_RESERVED3':'" + ewgObj[i].ewg_sum + "'," +
        "'PAIC_EXPECTATION':'" + ewgObj[i].paic_expectation + "'," +
        "'SECTION_ID':'" + ewgObj[i].ewg_section_id + "'," +
        "'YEAR_EP':'" + reportObj.yEAR_EP+"'},";
    }
    ewg_str = "["+ewg_str.substr(0,ewg_str.length-1)+"]";
    console.log(ewg_str);
    submitParams = {
        report : report_src,
        ewg_list : ewg_str,
        grade : grade_str
    };
    $("#loading").show();//显示等待页面
    $.ajax({
        type:"post",
        url:mpsurl+"/mobile/report/addReportG.do",
        dataType:"json",
        data:submitParams,
        success:function(json){
        	$("#loading").hide();//关闭等待页面
        	if(json.resultCode=="500600"){
        		GetOkPf();
        		//autoClosePrompt(json.HR_SSTEXT_TEXT);
        		setPromptForInput(json.HR_SSTEXT_TEXT);
        	}else{
        		if(json.resultCode=="500702" || json.resultCode=="500802" || json.resultCode=="500803"){
	        		var url = "/mobile/kpi/kpi-toScore.html?report_date="+report_date;
	            	checkLogin(json.resultCode,url,json.resultMessage);
            	}else
            		GetOkPf();
        			//autoClosePrompt(json.resultMessage);
        			setPromptForInput(json.resultMessage);
        	}
        },
        error: function (xhr, textStatus, errorThrown) {
           GetOkPf();//得到点击效果！
           $("#loading").hide();
           //autoClosePrompt("网络连接异常");
           setPromptForInput("网络异常");
		}
    });
}
var tis;
function submit (){
	ClearOkPf();
    if(check()){
    	$("#tis").html(tis);
    	$("#maskNode").show();
    }
}
function check(){
    var scoreEdits = $(".edit-score"), score;
    for(var i=0; i<scoreEdits.length; i++){
        score = $(scoreEdits[i]).val();
        if(score==""){
            //alert("请完成所有关键工作计划的评分再提交");
            //autoClosePrompt("请完成所有关键工作计划的评分再提交");
            setPromptForInput("请完成所有关键工作计划的评分再提交");
            GetOkPf();
            return false;
        } else if(!(score>=0 && score<=100)) {
        	//autoClosePrompt("评分范围为0~100，请输入正确的分数");
        	setPromptForInput("评分范围为0~100，请输入正确的分数");
            //alert("评分范围为0~100，请输入正确的分数");
            GetOkPf();
            return false;
        }
        if(score=="0"){
    		tis="您有评分项评分为0分";
    	}else{
    		tis="";
    	}	
    }
   
    if(! /^\d\.?\d$/.test($("#J-StaffNum").text())){
        //alert("请拖动标尺对您的本月汇报评分");
        //autoClosePrompt("请拖动标尺对您的本月汇报评分");
        setPromptForInput("请拖动标尺对您的本月汇报评分");
        GetOkPf();
        return false;
    }

    
    return true;
}
//提交
function submitData (){
	ClearOkPf();
    var submitParams,
        grade={
            "EP_APPRAISAL_ID" : pageData.report.ep_appraisal_id || "",
            "EP_RATING_MON" : $("#J-StaffNum").text(),
            "EP_RATING_M_A" : $("#opinionMsg").attr("data-rd"),
            "EP_RATING_M_B" : $("#opinionMsg").text(),
            "MONTH_EP" : pageData.report.eVA_MONTH_EP || "",
            "YEAR_EP" : pageData.report.yEAR_EP || "",
            "PAIC_SUM_SELF_RATE" : $("#totalScore").text()
        };
    var grade_str = "{'EP_APPRAISAL_ID':'"+ pageData.report.ep_appraisal_id +"',"+
            "'EP_RATING_MON':'" +$("#J-StaffNum").text() +"',"+
            "'EP_RATING_M_A':'" + $("#opinionMsg").attr("data-rd") +"',"+
            "'EP_RATING_M_B':'" + $("#opinionMsg").text() +"',"+
            "'MONTH_EP':'" + pageData.report.eVA_MONTH_EP  +"',"+
            "'YEAR_EP':'" + pageData.report.yEAR_EP +"',"+
            "'PAIC_SUM_SELF_RATE':'" + $("#totalScore").text() +"'}";

    $(".edit-score").forEach(function(node){
        node = $(node);
        var index = node.attr("data-index");
        pageData.ewg[index].ewg_self_rating = node.val();
    });
    
    var reportObj = pageData.report;
    
    var report_src = "{'EMPLID':'" + reportObj.eMPLID + "'," +
	    "'EP_APPRAISAL_ID':'" + reportObj.ep_appraisal_id + "'," +
	    "'EP_MANAGER1_ID':'" + reportObj.eP_MANAGER1_ID + "'," +
	    "'EP_MANAGER2_ID':'" + reportObj.eP_MANAGER2_ID + "'," +
	    "'EP_MANAGER3_ID':'" + reportObj.eP_MANAGER3_ID + "'," +
	    "'EP_TEMPLATE_ID':'" + reportObj.eP_TEMPLATE_ID + "'," +
	    "'EVA_GROUP_ID':'" + reportObj.eVA_GROUP_ID + "'," +
	    "'GRADED_CYC':'" + reportObj.gRADED_CYC + "'," +
	    "'MONTH_EP':'" + reportObj.eVA_MONTH_EP + "'," +
	    "'PAIC_MON_STATUS':'SUBM'," +
	    "'YEAR_EP':'" + reportObj.yEAR_EP + "'}";
    
    var ewg_str="";
    var ewgObj = pageData.ewg;
    for(var i=0;i<ewgObj.length;i++){
    	ewg_str = ewg_str +"{'CONTENT_DESCR':'"+ewgObj[i].ewg_descr+"',"+
    	"'EP_APPRAISAL_ID':'" + reportObj.ep_appraisal_id + "'," +
        "'EP_TRK_STATUS':'" + ewgObj[i].ewg_status + "'," +
        "'EVA_WEIGHT':'" + ewgObj[i].ewg_weight + "'," +
        "'PAIC_SELF_RATING':'" + ewgObj[i].ewg_self_rating + "'," +
        "'MONTH_EP':'" + reportObj.eVA_MONTH_EP + "'," +
        "'PAIC_EP_RESERVED1':'" + ewgObj[i].ewg_rea + "'," +
        "'PAIC_EP_RESERVED2':'" + ewgObj[i].ewg_nco + "'," +
        "'PAIC_EP_RESERVED3':'" + ewgObj[i].ewg_sum + "'," +
        "'PAIC_EXPECTATION':'" + ewgObj[i].paic_expectation + "'," +
        "'SECTION_ID':'" + ewgObj[i].ewg_section_id + "'," +
        "'YEAR_EP':'" + reportObj.yEAR_EP+"'},";
    }
    ewg_str = "["+ewg_str.substr(0,ewg_str.length-1)+"]";
    submitParams = {
        report : report_src,
        ewg_list : ewg_str,
        grade : grade_str
    };
//    console.log(submitParams);
    $("#loading").show();//显示等待页面
    $.ajax({
        type:"post",
        url:mpsurl+"/mobile/report/addReportG.do",
        dataType:"json",
        data:submitParams,
        success:function(json){
        	$("#loading").hide();//关闭等待页面
        	if(json.resultCode=="500600"){
        		$("#maskNode").hide();
        		//autoClosePrompt(json.HR_SSTEXT_TEXT);
        		if(json.FLAG=="A"){
        			setPromptForInput("提交成功");
        		}else{
        			setPromptForInput("网络繁忙");
        		}
        		setTimeout(function(){
        			//location.href="/mobile/kpi/kpi-todo.html?report_date="+report_date;
        			var param = "report_date="+ report_date;
					gotoLocation("/mobile/kpi/kpi-todo.html",param);
        		},2000);
        	}
        	else{
        		$("#maskNode").hide();
        		if(json.resultCode=="500702" || json.resultCode=="500802" || json.resultCode=="500803"){
	        		var url = "/mobile/kpi/kpi-toScore.html?report_date="+report_date;
	            	checkLogin(json.resultCode,url,"");
            	}else{
        			//autoClosePrompt(json.resultMessage);
        			setPromptForInput(json.resultMessage);
        			GetOkPf();
        		}
        	}
        },
         error: function (xhr, textStatus, errorThrown) {
            GetOkPf();//得到点击效果！
            $("#loading").hide();
            //autoClosePrompt("网络连接异常");
            setPromptForInput("网络异常");
		}
    });
}

function countSum (){
    var scoreEdits = $(".edit-score"), total= 0, score;
    for(var i=0; i<scoreEdits.length; i++){
        score = $(scoreEdits[i]).val() || 0;
        //校验输入分数 begin
	    if(score.length>1&score.substring(0,1)=="0"){
			score = score.substring(1);
			$(scoreEdits[i]).val(score);
		}
		var t = /^((\d)|(\d{2})|(100))$/;
		if(!t.test(score)){
			score = score.replace(/\D/,"");
			score = score.substring(0,score.length-1);
			$(scoreEdits[i]).val(score);
			//autoClosePrompt("请输入0~100之间的数");
			setPromptForInput("请输入0~100之间的数");
		}
		//end
        
        if((score>=0 && score<=100)) {
            if(!isNaN($(scoreEdits[i]).attr("data-weight"))){
            	total += (score * 1) * $(scoreEdits[i]).attr("data-weight");
            }
        }
    }
    $("#totalScore").text(total.toFixed(2));
}

//初始化评分标尺
function initGradeStaff(data){
    var resultCode = data.resultCode;
    if(resultCode == "500600"){
        stafArray = data.value;
    }else{
    	var url = "/mobile/kpi/kpi-toScore.html?report_date="+report_date;
        checkLogin(data.resultCode,url,data.resultMessage||"请求失败");
    }
    // 需要先初始化标尺评分，然后渲染和加载页面其它内容

    loadPageData();
    bindEvent();
}
// 拨动标尺时对评价信息进行切换
function setOpinionMsg(fraction){
    fraction = new Number(fraction).toFixed(1);
    for(var i= 0; i<stafArray.length; i++){
        var sItem = stafArray[i];
        if(fraction >= sItem.s1 && fraction <= sItem.s2){
            $("#opinionMsg").text(sItem.descr).attr("data-rd", sItem.rating_descr);
            $("#J-StaffNum").text(fraction);
			var offsetX = -101 - new Number(((fraction - 2.7) * 100)).toFixed(0);
		    $("#J-Staff").find(".staff-img-move").css("left",offsetX);
            break;
        }
    }
    iscroll();
}

function show(){
    $('#bdate').scroller('show');
}
function change(){
    $("#month").text($("#bdate").val().substr(4));
}
/**
 *  将一位日期显示成两位
 */
function formatDate(num){
    num = ""+num;
    return num.length <=1 ? "0"+num : num;
}
function back(){
    //history.back();
    //location.href="/mobile/kpi/kpi-todo.html?report_date="+report_date;
    var param = "report_date="+ report_date;
	gotoLocation("/mobile/kpi/kpi-todo.html",param);
}
function iscroll(){
	var wh = $(window).height()-90-112; 
	if(myiscroll instanceof iScroll)
		myiscroll.destroy();
	$("#content").css("height",wh+"px");
	myiscroll = new iScroll("content",{bounce:false});
}
/*
function autoClosePrompt(message){
    var promptTemple = "<div class='check-prompt' id='CheckPrompt'>" +
		"<div class='check-prompt-bg'></div>" +
		"<div class='check-prompt-txt'>" + message + "</div>" +
		"</div>";
    $("body").append(promptTemple);
    setTimeout(function(){
        $("#CheckPrompt").remove("slow");
    }, 3000);
}
*/
function ClearOkPf(){
	$("#save").hide();
	$("#Nosave").show();
	$("#submit").hide();
	$("#Nosubmit").show();
}

function GetOkPf(){
	$("#save").show();
	$("#Nosave").hide();
	$("#submit").show();
	$("#Nosubmit").hide();
}
